# coding: utf-8
# Magic comment en 1a linia perquè cadenes literals siguin UTF-8 i no Ascii (així podem posar accents en Windows)
#           Opcions:-w=Activar Warnings. -KU=$KCODE = "U" --> fa que els strings per defecte siguin UTF-8, NO te efecte en Ruby 1.9 !
#!/usr/bin/env ruby -w

require './104/base.rb'

$myname = "ical_join"

help = <<EODOC
Usage: #{$myname} Directory_ics [-s]
Joins *.ics calendars in Directori_ics into one big file out_joined.ics.
EODOC

if ARGV.length < 1  then  puts help; exit; end	
dir = File.absolute_path(ARGV[0].encode($ee))
if !File.directory?(dir) then
	puts "FATAL ERROR: Directory '#{dir}' does not exist."
	exit
end	

numf = 0
out = File.new("out_joined.ics", "w")

if ARGV[1] == '-s' then
	filter = File.join("**", "*.ics")  # "**"=Matches directories recursively. Documented in Dir.glob                
else
	filter = File.join("*.ics") # Example with more extensions: "*.{jpg,png}"                
end

Dir.chdir(dir){ |path|
Dir.glob(filter){ |file|
	afile = "#{dir}/#{file}"
	afile.gsub!(/\//, "\\")  # / -> \ # !!! Al reves per Linux ???
	k_puts afile
	numf += 1
	lines = File.readlines(afile)
	event = 0
	lines.each{|line|
		if line.eql?("BEGIN:VEVENT\n") then event += 1 end
		if event == 1 then 
			out.puts line
		elsif (numf == 1) and (event == 0) then 
			out.puts line # Copiem del 1r fitxer BEGIN:VCALENDAR i primeres linies de propietats.			
		end
		if line.eql?("END:VEVENT\n") then event += 1 end		
		}
	if event != 2 then puts "ERROR: File #{afile} has not only one VEVENT (event=#{event})" ; exit; end
}
}

out.puts "END:VCALENDAR\n"
out.close
puts "Joined #{numf} files."



